﻿namespace IOP.Pulsar.MQTT.Abstractions
{
    /// <summary>
    /// 通配符扩展
    /// </summary>
    public static class WildcardExtension
    {
        /// <summary>
        /// 字符串匹配
        /// </summary>
        /// <param name="text"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static bool MatchTopicWildcard(this string text, string pattern)
        {
            var textBox = text.Split('/');
            var patternBox = pattern.Split('/');
            var max = textBox.Length > patternBox.Length ? textBox.Length : patternBox.Length;
            var newText = new string[max];
            var newPattern = new string[max];
            for (int m = 0; m < max; m++)
            {
                if (m < textBox.Length) newText[m] = textBox[m];
                else newText[m] = "";
                if (m < patternBox.Length) newPattern[m] = patternBox[m];
                else newPattern[m] = "";
            }
            for (int i = 0; i < max; i++)
            {
                if (newPattern[i] == "+") continue;
                if (newPattern[i] == "#") break;
                if (newPattern[i] != newText[i]) return false;
            }
            return true;
        }
    }
}
